import React, { useState } from 'react';
import {
    Modal,
    Form,
    Input,
    Select,
    Row,
    Col,
    Table,
    Button,
    Space,
    Popconfirm,
    Tag,
    Divider,
    message
} from 'antd';
import {
    PlusOutlined,
    EditOutlined,
    DeleteOutlined
} from '@ant-design/icons';
import { ApiMapperModal } from './ApiMapperModal';
import type { ApiInfo, ApiMapper, ApiParamInfo } from '../txs/types';
import { getObject, toast, requestBody, apis } from "@/service/common";

// API类型选项
const apiTypeOptions = [
    // { label: 'REST', value: 'REST' },
    // { label: 'GraphQL', value: 'GraphQL' },
    // { label: 'SOAP', value: 'SOAP' },
];

// 响应类型选项
const responseTypeOptions = [
    { label: 'LIST', value: 0 },
    { label: 'JSON', value: 1 },
];

interface ApiInfoModalProps {
    visible: boolean;
    onCancel: () => void;
    onOk: (values: ApiInfo) => void;
    initialValues?: ApiInfo;
    confirmLoading?: boolean;
}

export const ApiInfoModal: React.FC<ApiInfoModalProps> = ({
    visible,
    onCancel,
    onOk,
    initialValues,
    confirmLoading,
}) => {
    const [form] = Form.useForm();
    const [mappers, setMappers] = useState<ApiMapper[]>(initialValues?.mappers || []);
    const [mapperModalVisible, setMapperModalVisible] = useState(false);
    const [currentMapper, setCurrentMapper] = useState<ApiMapper | null>(null);
    const [apiGroupOptions, setApiGroupOptions] = useState<{ label: string; value: number }[]>([{
        label: '无分组', value: 0
    }]);

    const getGroupList = () => {
        getObject({ url: apis.apiServer.groupList }).then(({ data }) => {
            if (data instanceof Array) {
                const ago = [{ label: '无分组', value: 0 }]
                data.forEach(d => {
                    ago.push({ label: d.name, value: d.id })
                })
                setApiGroupOptions(ago || []);
            }

        })
    }

    React.useEffect(() => {
        if (visible) {
            form.resetFields();
            getGroupList()
            if (initialValues) {
                form.setFieldsValue(initialValues);
                setMappers(initialValues.mappers || []);
            } else {
                setMappers([]);
            }
        }
    }, [visible, initialValues, form]);

    const handleSubmit = () => {
        form.validateFields().then(values => {
            const apiData = {
                ...values,
                id: initialValues?.id,
                mappers: mappers
            };
            requestBody({ url: apis.apiServer.save, data: apiData })
                .then(({ data }) => {
                    onOk(data);
                    toast.success("保存成功");
                });

        });
    };

    // Mapper操作函数
    const handleAddMapper = () => {
        setCurrentMapper(null);
        setMapperModalVisible(true);
    };

    const handleEditMapper = (mapper: ApiMapper) => {
        setCurrentMapper(mapper);
        setMapperModalVisible(true);
    };

    const handleDeleteMapper = (id: string) => {
        setMappers(mappers.filter(m => m.code !== id));
        toast.success('Mapper删除成功');
    };

    const handleSaveMapper = (mapper: ApiMapper) => {

        if (currentMapper) {
            // 更新现有Mapper
            setMappers(mappers.map(m => m.code === currentMapper.code ? mapper : m));
            toast.success('Mapper更新成功');
        } else {
            if (mappers.find(m => m.code === mapper.code)) {
                toast.error(mapper.code + ' 编码已存在');
                return
            }
            // 添加新Mapper
            setMappers([...mappers, {
                ...mapper
            }]);
            toast.success('Mapper添加成功');
        }
        setMapperModalVisible(false);
    };

    // Mapper表格列配置
    const mapperColumns = [
        {
            title: 'Mapper名称',
            dataIndex: 'name',
            key: 'name',
        },
        {
            title: '编码',
            dataIndex: 'code',
            key: 'code',
        },
        {
            title: '响应类型',
            dataIndex: 'responseType',
            key: 'responseType',
            render: (type: number) => (
                responseTypeOptions.find(opt => opt.value === type)?.label || type
            ),
        },
        {
            title: '参数数量',
            dataIndex: 'paramInfos',
            key: 'paramCount',
            render: (params: ApiParamInfo[]) => params?.length || 0,
        },
        {
            title: '操作',
            key: 'action',
            render: (_: any, record: ApiMapper) => (
                <Space size="middle">
                    <Button
                        type="link"
                        size="small"
                        icon={<EditOutlined />}
                        onClick={() => handleEditMapper(record)}
                    >
                        编辑
                    </Button>
                    <Popconfirm
                        title="确定要删除此Mapper吗？"
                        onConfirm={() => handleDeleteMapper(record.code)}
                        okText="确定"
                        cancelText="取消"
                    >
                        <Button
                            type="link"
                            size="small"
                            icon={<DeleteOutlined />}
                            danger
                        >
                            删除
                        </Button>
                    </Popconfirm>
                </Space>
            ),
        },
    ];

    return (
        <>
            <Modal
                title={initialValues?.id ? '编辑API' : '添加API'}
                visible={visible}
                onOk={handleSubmit}
                onCancel={onCancel}
                okText="保存"
                cancelText="取消"
                width={800}
                destroyOnClose
                confirmLoading={confirmLoading}
                maskClosable={false}
            >
                <Form
                    form={form}

                >
                    <Row gutter={16}>
                        <Col span={12}>
                            <Form.Item
                                label="API名称"
                                name="name"
                                rules={[{ required: true, message: '请输入API名称' }]}
                            >
                                <Input placeholder="例如: 用户查询API" />
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item
                                label="路径"
                                name="path"
                                rules={[{ required: true, message: '请输入API路径' }]}
                            >
                                <Input placeholder="例如: /api/user" />
                            </Form.Item>
                        </Col>
                    </Row>
                    <Row gutter={16}>

                        <Col span={12}>
                            <Form.Item
                                label="分组"
                                name="gid"
                                rules={[{ required: true, message: '请选择分组' }]}
                            >
                                <Select options={apiGroupOptions} placeholder="请选择分组" />
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item
                                label="类型"
                                name="type"
                                rules={[{ required: false, message: '请选择API类型' }]}
                            >
                                <Select options={apiTypeOptions} placeholder="请选择API类型" />
                            </Form.Item>
                        </Col>
                    </Row>

                    <Divider orientation="left">Mapper配置</Divider>

                    <div style={{ marginBottom: 16 }}>
                        <Button
                            type="primary"
                            icon={<PlusOutlined />}
                            onClick={handleAddMapper}
                        >
                            添加Mapper
                        </Button>
                    </div>

                    <Table
                        columns={mapperColumns}
                        dataSource={mappers}
                        rowKey="id"
                        pagination={false}
                        size="small"
                        bordered
                        locale={{
                            emptyText: '暂无Mapper配置'
                        }}
                    />
                </Form>
            </Modal>

            {/* Mapper编辑模态框 */}
            <ApiMapperModal
                visible={mapperModalVisible}
                onCancel={() => setMapperModalVisible(false)}
                onOk={handleSaveMapper}
                initialValues={currentMapper || undefined}
            />
        </>
    );
};
